package httpUtils;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: Utils
 * @BelongsPackage: httpUtils
 * @Author: gejingyu
 * @Date: 2024/1/10
 * @Description: 基于RestfulTemplate处理http请求
 */

public class RestfulUtil {

    /**
     * 执行post类型请求，返回请求结果字符串
     *
     * @param url      访问接口地址
     * @param jsonData String类型的jsonData请求参数
     * @return 请求结果
     */
    public static String postMethodForString(String url, String jsonData) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        return exchange.getBody();
    }

    /**
     * 执行post类型请求，返回结果列表
     *
     * @param url      请求接口地址
     * @param jsonData String类型的jsonData请求参数
     * @return List&lt;Map&lt;String, Object&gt;&gt;类型的请求结果列表
     */
    public static List<Map<String, Object>> postMethodForListMap(String url, String jsonData) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        ParameterizedTypeReference<List<Map<String, Object>>> responseType =
                new ParameterizedTypeReference<List<Map<String, Object>>>() {
                };

        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<List<Map<String, Object>>> exchange =
                restTemplate.exchange(url, HttpMethod.POST, entity, responseType);

        return exchange.getBody();
    }

    /**
     * 执行post请求，返回结果结果
     *
     * @param url      请求接口地址
     * @param jsonData String类型的jsonData请求参数
     * @return Map&lt;String, Object&gt;类型的请求结果列表
     */
    public static Map<String, Object> postMethodForMap(String url, String jsonData) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        ParameterizedTypeReference<Map<String, Object>> responseType =
                new ParameterizedTypeReference<Map<String, Object>>() {
                };

        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map<String, Object>> exchange =
                restTemplate.exchange(url, HttpMethod.POST, entity, responseType);

        return exchange.getBody();
    }
}
